package com.rand.beauty;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import cn.domob.android.ads.DomobAdEventListener;
import cn.domob.android.ads.DomobAdView;
import cn.domob.android.ads.DomobAdManager.ErrorCode;

import com.dodola.model.DuitangInfo;
import com.dodowaterfall.Helper;
import com.example.android.bitmapfun.util.ImageCache;
import com.example.android.bitmapfun.util.ImageFetcher;
import com.haarman.listviewanimations.ArrayAdapter;
import com.rand.beauty.R;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.RequestType;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.UMSsoHandler;
import com.umeng.socialize.controller.UMWXHandler;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.TencentWBSsoHandler;

public class DetailAblumListActivity extends Activity {

	private GoogleCardsAdapter mGoogleCardsAdapter;
	private LinkedList<DuitangInfo> mInfos;
	private ContentTask mTask = new ContentTask(this);
	private ImageFetcher mImageFetcher;
	private String mSign;
	protected static final int WEB_DOWNLOAD = 1;
	protected static final int WEB_WALLPAPER = 2;
	private DomobAdView mAdview320x50;
	private Context mContext;
	private UMSocialService mController;
	private final String mShareTargetUrl = "http://zhushou.360.cn/detail/index/soft_id/941474";// 360手机助手的下载页
	public static final String PUBLISHER_ID = "56OJw0oouNI2Bb3sTp";
	public static final String FlexPID = "16TLuJHvApkyYNU-bmLwlFzk";

	private class ContentTask extends
			AsyncTask<String, Integer, List<DuitangInfo>> {

		private Context mContext;

		public ContentTask(Context context) {
			super();
			mContext = context;
		}

		@Override
		protected List<DuitangInfo> doInBackground(String... params) {
			try {
				return parseNewsJSON(params[0]);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(List<DuitangInfo> result) {
			hideProgressBar();

			for (DuitangInfo info : result) {
				mInfos.addLast(info);
			}

			mGoogleCardsAdapter.notifyDataSetChanged();
		}

		@Override
		protected void onPreExecute() {
		}

		public List<DuitangInfo> parseNewsJSON(String url) throws IOException {
			List<DuitangInfo> duitangs = new ArrayList<DuitangInfo>();
			String json = "";
			if (Helper.checkConnection(mContext)) {
				try {
					json = Helper.getStringFromUrl(url);

				} catch (IOException e) {
					Log.e("IOException is : ", e.toString());
					e.printStackTrace();
					return duitangs;
				}
			}

			try {
				JSONObject jsonObject = new JSONObject(json)
						.getJSONObject("data");
				JSONArray jsonArray = jsonObject.getJSONArray("picture_list");
				String ablum = jsonObject.getString("nav_name");

				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject _json = (JSONObject) jsonArray.opt(i);
					String pic_small = _json.getString("img_src_ac");
					// String pic_small = _json.getString("img_src_small");
					String pic_1600 = _json.getString("img_src_1600");
					String pic_name = _json.getString("picture_name");
					String pic_sign = _json.getString("picture_sign");
					int height = _json.getInt("picture_height");
					int width = _json.getInt("picture_width");

					if (!KeyFilterUtils.isCanShow(pic_name)) {
						continue;
					}

					DuitangInfo newsInfo1 = new DuitangInfo();
					newsInfo1.setMsg(pic_name);
					newsInfo1.setAlbid(ablum);
					newsInfo1.setIsrc(pic_small);
					newsInfo1.setHeight(height);
					newsInfo1.setWidth(width);
					newsInfo1.setSign(pic_sign);
					newsInfo1.setBig_pic(pic_1600);

					if (pic_sign.equalsIgnoreCase(mSign)) {
						duitangs.add(0, newsInfo1);
					} else {
						duitangs.add(newsInfo1);
					}

					mImageFetcher.startLoadImageForBack(pic_small);
				}
			} catch (org.json.JSONException e) {
			}
			return duitangs;
		}
	}

	private void hideProgressBar() {
		ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressbar);
		progressBar.setVisibility(View.INVISIBLE);
		LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) progressBar
				.getLayoutParams();
		lp.height = 0;
		lp.topMargin = 0;
		progressBar.setLayoutParams(lp);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.activity_googlecards);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.titlebtn);

		ListView listView = (ListView) findViewById(R.id.activity_googlecards_listview);

		mGoogleCardsAdapter = new GoogleCardsAdapter(this);
		mImageFetcher = new ImageFetcher(this, 400);
		mImageFetcher.setImageCache(new ImageCache(this, "detaillist"));
		mImageFetcher.setLoadingImage(R.drawable.empty_photo);

		listView.setAdapter(mGoogleCardsAdapter);

		Intent intent = getIntent();
		String url = intent.getStringExtra("ablum_url");
		mSign = intent.getStringExtra("pic_sign");
		mTask.execute(url);
		if (KeyFilterUtils.isShowAD()) {
			initAD();
		}

		initMoreBtn();
		initBackBtn();
		HandleLongPress();
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onPageStart("detailpage");
		MobclickAgent.onResume(this);
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd("detailpage");
		MobclickAgent.onPause(this);
	}

	private void initMoreBtn() {
		Button btn = (Button) findViewById(R.id.more_btn);
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(DetailAblumListActivity.this,
						PreferencesSetting.class);

				Bundle bundle = new Bundle();
				intent.putExtras(bundle);
				startActivity(intent);
			}

		});
	}

	private void initBackBtn() {
		Button btn = (Button) findViewById(R.id.back_btn);
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();

			}

		});
	}

	public void initAD() {

		RelativeLayout adContainer = (RelativeLayout) findViewById(R.id.adcontainer);

		// Create ad view
		mAdview320x50 = new DomobAdView(this,
				PullToRefreshSampleActivity.PUBLISHER_ID,
				PullToRefreshSampleActivity.FlexPID,
				DomobAdView.INLINE_SIZE_FLEXIBLE);

		mAdview320x50.setKeyword("game");
		mAdview320x50.setUserGender("male");
		mAdview320x50.setUserBirthdayStr("1970-08-08");

		Integer randcode = (int) (Math.random() * 10000000);
		mAdview320x50.setUserPostcode(randcode.toString());

		RelativeLayout.LayoutParams layout = new RelativeLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		adContainer.addView(mAdview320x50, layout);

		adContainer.setVisibility(View.VISIBLE);
		mAdview320x50.setVisibility(View.VISIBLE);

		mAdview320x50.setAdEventListener(new DomobAdEventListener() {

			@Override
			public void onDomobAdReturned(DomobAdView adView) {
				Log.i("DomobSDKDemo", "onDomobAdReturned");
			}

			@Override
			public Context onDomobAdRequiresCurrentContext() {
				return DetailAblumListActivity.this;
			}

			@Override
			public void onDomobAdClicked(DomobAdView arg0) {
				MobclickAgent.onEvent(mContext, "click", "sub_page_ad");
			}

			@Override
			public void onDomobAdFailed(DomobAdView arg0, ErrorCode arg1) {
			}

			@Override
			public void onDomobAdOverlayDismissed(DomobAdView arg0) {
			}

			@Override
			public void onDomobAdOverlayPresented(DomobAdView arg0) {
			}

			@Override
			public void onDomobLeaveApplication(DomobAdView arg0) {
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		/** 使用SSO授权必须添加如下代码 */
		UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(
				requestCode);
		if (ssoHandler != null) {
			ssoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
	}

	private class GoogleCardsAdapter extends ArrayAdapter<Integer> {
		public GoogleCardsAdapter(Context context) {
			mContext = context;
			mInfos = new LinkedList<DuitangInfo>();
		}

		private void initShare() {
			if (mController == null) {
				mController = UMServiceFactory.getUMSocialService(
						"com.umeng.share", RequestType.SOCIAL);
				mController.getConfig().setPlatformOrder(SHARE_MEDIA.WEIXIN,
						SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QZONE,
						SHARE_MEDIA.SINA, SHARE_MEDIA.SMS, SHARE_MEDIA.DOUBAN);
				mController.getConfig().supportQQPlatform(
						DetailAblumListActivity.this, mShareTargetUrl);
				mController.getConfig().setQZoneSsoHandler(
						new QZoneSsoHandler(DetailAblumListActivity.this));
				mController.getConfig()
						.setSsoHandler(new TencentWBSsoHandler());

				mController.getConfig().removePlatform(SHARE_MEDIA.QQ);

				mController.setAppWebSite(SHARE_MEDIA.QZONE, mShareTargetUrl);

				// wx967daebe835fbeac是你在微信开发平台注册应用的AppID, 这里需要替换成你注册的AppID
				String appID = "wx1db33ca36f8a08a1";
				// 微信图文分享必须设置一个url
				// 添加微信平台，参数1为当前Activity, 参数2为用户申请的AppID, 参数3为点击分享内容跳转到的目标url
				UMWXHandler wxHandler = mController.getConfig()
						.supportWXPlatform(DetailAblumListActivity.this, appID,
								mShareTargetUrl);
				wxHandler.setWXTitle("这个妹子还不错哦...");
				// 支持微信朋友圈
				UMWXHandler circleHandler = mController.getConfig()
						.supportWXCirclePlatform(DetailAblumListActivity.this,
								appID, mShareTargetUrl);
				circleHandler.setCircleTitle("这个妹子还不错哦..。");
			}
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolder viewHolder;
			View view = convertView;
			if (view == null) {
				view = LayoutInflater.from(mContext).inflate(
						R.layout.activity_googlecards_card, parent, false);

				viewHolder = new ViewHolder();
				viewHolder.textView = (TextView) view
						.findViewById(R.id.activity_googlecards_card_textview);
				view.setTag(viewHolder);
				viewHolder.linearView = view;
				viewHolder.imageView = (ImageView) view
						.findViewById(R.id.activity_googlecards_card_imageview);

				final ImageButton v1 = (ImageButton) view
						.findViewById(R.id.share_btn);

				v1.setImageDrawable(getResources()
						.getDrawable(R.drawable.share));

				v1.setOnTouchListener(new OnTouchListener() {
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						if (event.getAction() == MotionEvent.ACTION_DOWN) {
							v1.setBackgroundResource(R.drawable.list_item_btn_p);
						} else if (event.getAction() == MotionEvent.ACTION_CANCEL
								|| event.getAction() == MotionEvent.ACTION_UP) {
							v1.setBackgroundResource(R.drawable.list_item_btn_n);
						}

						if (event.getAction() == MotionEvent.ACTION_UP) {
							initShare();

							int pos = (Integer) v.getTag();
							// 设置分享内容
							DuitangInfo info = mInfos.get(pos);
							String appName = getResources().getString(
									R.string.app_name);
							String msg = "这个妹子还不错哦 ----来自《" + appName
									+ "》 点击下载：" + mShareTargetUrl;
							mController.setShareContent(msg);

							mController.setShareMedia(new UMImage(
									DetailAblumListActivity.this, mImageFetcher
											.getBitmapFormMem(info.getIsrc())));
							// 设置分享图片

							mController.openShare(DetailAblumListActivity.this,
									false);

							MobclickAgent.onEvent(mContext, "click", "share");
						}

						return false;
					}

				});

				final ImageButton v2 = (ImageButton) view
						.findViewById(R.id.download_btn);
				v2.setImageDrawable(getResources().getDrawable(
						R.drawable.download));

				v2.setOnTouchListener(new OnTouchListener() {
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						if (event.getAction() == MotionEvent.ACTION_DOWN) {
							v2.setBackgroundResource(R.drawable.list_item_btn_p);
						} else if (event.getAction() == MotionEvent.ACTION_CANCEL
								|| event.getAction() == MotionEvent.ACTION_UP) {
							v2.setBackgroundResource(R.drawable.list_item_btn_n);
						}

						if (event.getAction() == MotionEvent.ACTION_UP) {
							int pos = (Integer) v.getTag();
							DuitangInfo info = mInfos.get(pos);
							SaveToAblum(info.getBig_pic());
							MobclickAgent
									.onEvent(mContext, "click", "download");
						}

						return false;
					}

				});

				final ImageButton v3 = (ImageButton) view
						.findViewById(R.id.wallpaper_btn);
				v3.setImageDrawable(getResources().getDrawable(
						R.drawable.wallpaper));

				v3.setOnTouchListener(new OnTouchListener() {
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						if (event.getAction() == MotionEvent.ACTION_DOWN) {
							v3.setBackgroundResource(R.drawable.list_item_btn_p);
						} else if (event.getAction() == MotionEvent.ACTION_CANCEL
								|| event.getAction() == MotionEvent.ACTION_UP) {
							v3.setBackgroundResource(R.drawable.list_item_btn_n);
						}

						if (event.getAction() == MotionEvent.ACTION_UP) {
							int pos = (Integer) v.getTag();
							DuitangInfo info = mInfos.get(pos);
							SetToWallPaper(info.getBig_pic());
							MobclickAgent.onEvent(mContext, "click",
									"wallpaper");
						}

						return false;
					}

				});

				final ImageButton v4 = (ImageButton) view
						.findViewById(R.id.fav_btn);
				v4.setImageDrawable(getResources().getDrawable(R.drawable.fav));

				v4.setOnTouchListener(new OnTouchListener() {
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						if (event.getAction() == MotionEvent.ACTION_DOWN) {
							v4.setBackgroundResource(R.drawable.list_item_btn_p);
						} else if (event.getAction() == MotionEvent.ACTION_CANCEL
								|| event.getAction() == MotionEvent.ACTION_UP) {
							v4.setBackgroundResource(R.drawable.list_item_btn_n);
						}

						if (event.getAction() == MotionEvent.ACTION_UP) {
							int pos = (Integer) v.getTag();
							DuitangInfo info = mInfos.get(pos);
							FavouritePic(info.getIsrc());
							MobclickAgent.onEvent(mContext, "click", "fav");
						}

						return false;
					}

				});

				viewHolder.v1 = v1;
				viewHolder.v2 = v2;
				viewHolder.v3 = v3;
				viewHolder.v4 = v4;

			} else {
				viewHolder = (ViewHolder) view.getTag();
			}

			DuitangInfo info = mInfos.get(position);
			viewHolder.textView.setText(info.getMsg());

			LayoutParams ps = viewHolder.imageView.getLayoutParams();
			int fitHeight = info.getHeight()
					* (parent.getWidth() - parent.getPaddingLeft()
							- parent.getPaddingRight()
							- viewHolder.linearView.getPaddingLeft() - viewHolder.linearView
								.getPaddingRight()) / info.getWidth();
			ps.height = fitHeight;
			viewHolder.imageView.setLayoutParams(ps);
			mImageFetcher.loadImage(info.getIsrc(), viewHolder.imageView);

			viewHolder.v1.setTag(position);
			viewHolder.v2.setTag(position);
			viewHolder.v3.setTag(position);
			viewHolder.v4.setTag(position);

			return view;
		}

		private class ViewHolder {
			TextView textView;
			ImageView imageView;
			View linearView;
			ImageButton v1;
			ImageButton v2;
			ImageButton v3;
			ImageButton v4;
		}

		@Override
		public int getCount() {
			return mInfos.size();
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

	}

	void FavouritePic(String url) {

		if (KeyFilterUtils.isFileInFavList(this, url)) {
			ToastUtil.showMessage(this, "已收藏");
		} else {
			Log.i("you click", "收藏");
			SaveImgToDo todo = new SaveImgToDo(DetailAblumListActivity.this);
			todo.Run(SaveImgToDo.WhatToDo.Favourite, url);
		}
	}

	void SaveToAblum(String url) {
		Log.i("you click", "保存");
		SaveImgToDo todo = new SaveImgToDo(DetailAblumListActivity.this);
		todo.Run(SaveImgToDo.WhatToDo.Save_To_Ablum, url);
	}

	void SetToWallPaper(String url) {
		Log.i("you click", "设置为壁纸");
		SaveImgToDo todo = new SaveImgToDo(DetailAblumListActivity.this);
		todo.Run(SaveImgToDo.WhatToDo.Save_To_SetWallPaper, url);
	}

	private void HandleLongPress() {
		ListView listView = (ListView) findViewById(R.id.activity_googlecards_listview);
		listView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
			public void onCreateContextMenu(ContextMenu conMenu, View view,
					ContextMenuInfo info) {
				AdapterContextMenuInfo itemInfo = (AdapterContextMenuInfo) info;
				final String url = mInfos.get(itemInfo.position).getBig_pic();
				MenuItem.OnMenuItemClickListener handler = new MenuItem.OnMenuItemClickListener() {
					public boolean onMenuItemClick(MenuItem item) {
						// do the menu action
						switch (item.getItemId()) {
						case WEB_DOWNLOAD:
							SaveToAblum(url);
							break;
						case WEB_WALLPAPER:
							SetToWallPaper(url);
							break;
						}
						return true;
					}
				};

				Intent i = new Intent();
				MenuItem item = conMenu.add(0, WEB_DOWNLOAD, 0, "保存到相册")
						.setOnMenuItemClickListener(handler);
				item.setIntent(i);
				item = conMenu.add(0, WEB_WALLPAPER, 0, "设置为壁纸")
						.setOnMenuItemClickListener(handler);
				item.setIntent(i);
				conMenu.setHeaderTitle("提示");
			}
		});
	}
}
